/**
 *
 */
package com.thinkgem.javamg.modules.busi.service;

import com.thinkgem.javamg.common.service.CrudService;
import com.thinkgem.javamg.common.utils.StringUtils;
import com.thinkgem.javamg.modules.busi.dao.NewsAlbumDao;
import com.thinkgem.javamg.modules.busi.dao.NewsDao;
import com.thinkgem.javamg.modules.busi.entity.News;
import com.thinkgem.javamg.modules.busi.entity.NewsAlbum;
import com.thinkgem.javamg.modules.busi.utils.JsoupUtil;
import com.thinkgem.javamg.modules.busi.utils.WordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 资讯Service
 *
 * @author zengzy
 * @version 2017-09-13
 */
@Service
@Transactional(readOnly = true)
public class NewsService extends CrudService<NewsDao, News> {

    @Autowired
    private NewsAlbumDao newsAlbumDao;

    @Transactional(readOnly = false)
    public void save(News news) {
        if (StringUtils.isNotEmpty(news.getTitle())
                && StringUtils.isNotEmpty(news.getContent())
                && StringUtils.isNotEmpty(news.getSmallpicurl())
                && null != news.getTypeId()) {

            if (dao.isexist(news.getTitle()) > 0) {
                return;
            }

            //1、插入资讯主表
            news.setPublishTime(news.getAddtime());
            news.setAuthor("1872高球通");
            if (StringUtils.isEmpty(news.getPicurl())) {
                news.setPicurl(news.getSmallpicurl());
            }

            //去掉详情第一张图片
            news.setContent(JsoupUtil.removeFirstImg(news.getContent()));

            //提取关键字
            if (StringUtils.isEmpty(news.getTag()) && StringUtils.isNotEmpty(news.getContent())) {
                try {
                    news.setTag(WordUtil.getKeyWords(news.getContent()));
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            }
            dao.insert(news);

            //2、插入图集
            List<NewsAlbum> newsAlbumList = news.getNewsAlbumList();
            if (null != newsAlbumList && newsAlbumList.size() > 0) {
                for (NewsAlbum newsAlbum : newsAlbumList) {
                    newsAlbum.setNewsId(news.getId());
                    newsAlbum.setTitle(news.getTitle());
                    newsAlbumDao.insert(newsAlbum);
                }
            }
        }
    }

}